<!-- 外购入库生产入库单  purchase-receipt -->
<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="单据编号" prop="no">
        <el-input
          v-model="queryParams.no"
          placeholder="请输入单据编号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item prop="productBarCode" label="物料">
        <infinite-select
          v-model="queryParams.productBarCode"
          clearable
          filterable
          :api="ProductApi.getProductSimpleList"
          labelKey="name"
          valueKey="barCode"
          placeholder="请选择物料"
          class="!w-240px"
        />
      </el-form-item>
      <!-- <el-form-item label="物料代码" prop="productBarCode">
        <el-input
          v-model="queryParams.productBarCode"
          placeholder="请输入物料代码"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item> -->

      <el-form-item label="调出仓库" prop="fromWarehouseId">
        <el-select
          v-model="queryParams.fromWarehouseId"
          clearable
          filterable
          placeholder="请选择调出仓库"
          class="!w-240px"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="调入仓库" prop="toWarehouseId">
        <el-select
          v-model="queryParams.toWarehouseId"
          clearable
          filterable
          placeholder="请选择调入仓库"
          class="!w-240px"
        >
          <el-option
            v-for="item in warehouseList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="会计期间" prop="moveTime">
        <el-date-picker
          v-model="queryParams.moveTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表：已修复合计行计算逻辑 -->
  <ContentWrap>
    <el-table
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      row-key="id"
      :default-expand-all="isExpandAll"
      v-if="refreshTable"
    >
      <el-table-column label="调拨单号" min-width="200" align="center" prop="no" />
      <el-table-column label="调出仓库编号" align="center" min-width="160" prop="fromWarehouseId" />
      <el-table-column
        label="调出仓库名称"
        align="center"
        min-width="160"
        prop="fromWarehouseName"
      />
      <el-table-column label="调入仓库编号" align="center" prop="toWarehouseId" min-width="120" />
      <el-table-column label="调入仓库名称" align="center" prop="toWarehouseName" width="160" />
      <el-table-column label="物料长代码" align="center" prop="productBarCode" min-width="120" />
      <el-table-column label="物料名称" align="center" prop="productName" min-width="160" />
      <el-table-column label="规格型号" align="center" prop="productStandard" min-width="120" />
      <el-table-column label="产品单位名称" align="center" prop="productUnitName" min-width="120" />
      <el-table-column label="调拨数量" align="center" prop="count" min-width="120" />
      <el-table-column label="单位成本" align="center" prop="productPrice" />
      <el-table-column label="调拨金额" align="center" prop="productTotalPrice" min-width="120" />
      <el-table-column label="备注" align="center" prop="remark" />
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter2 } from '@/utils/formatTime'
import { FinanceApi } from '@/api/finance/index'
import download from '@/utils/download'
import { WarehouseApi, WarehouseVO } from '@/api/erp/stock/warehouse'
import { ProductApi, ProductVO } from '@/api/erp/product/product'

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 总条数
const queryParams = reactive({
  no: undefined,
  productBarCode: undefined,
  moveTime: undefined, // 日期范围将在这里被动态设置
  fromWarehouseId: undefined,
  toWarehouseId: undefined,
  pageNo: 1,
  pageSize: 10
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const isExpandAll = ref(true) // 是否展开，默认全部展开
const refreshTable = ref(true) // 重新渲染表格状态
const warehouseList = ref<WarehouseVO[]>([]) // 仓库列表

/**
 * @description: 计算并返回近7天的日期范围
 * @return {Array<string>} 一个包含两个字符串的数组，格式为 ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59']
 */
const getDefaultDateRange = () => {
  const endDate = new Date()
  const startDate = new Date()
  startDate.setDate(endDate.getDate() - 6) // 今天 - 6天 = 近7天

  // 格式化日期为 'YYYY-MM-DD'
  const formatDate = (date: Date) => {
    const year = date.getFullYear()
    const month = (date.getMonth() + 1).toString().padStart(2, '0')
    const day = date.getDate().toString().padStart(2, '0')
    return `${year}-${month}-${day}`
  }

  return [`${formatDate(startDate)} 00:00:00`, `${formatDate(endDate)} 23:59:59`]
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await FinanceApi.stockMovePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  // 1. 重置表单字段
  if (queryFormRef.value) {
    queryFormRef.value.resetFields()
  }
  // 2. 手动清空其他非日期范围的查询条件
  // 注意：resetFields 只会清空在 el-form-item 中定义了 prop 的字段
  queryParams.no = undefined
  queryParams.productBarCode = undefined
  queryParams.fromWarehouseId = undefined
  queryParams.toWarehouseId = undefined

  // 3. 重新设置日期范围为默认的近7天
  queryParams.moveTime = getDefaultDateRange()

  // 4. 执行查询
  handleQuery()
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    await message.exportConfirm()
    exportLoading.value = true
    const data = await FinanceApi.exportStockMoveExcel(queryParams)
    download.excel(data, '仓库调拨单.xls')
  } catch (error) {
    console.error('导出失败:', error)
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  // 在组件挂载后，设置日期范围的默认值
  queryParams.moveTime = getDefaultDateRange()
  // 加载仓库列表
  warehouseList.value = await WarehouseApi.getWarehouseSimpleList()
  // 执行初始查询
  getList()
})
</script>

<style scoped>
.ContentWrap {
  margin: 16px;
}

.el-table {
  width: 100%;
  margin-top: 16px;
}

.el-pagination {
  margin-top: 16px;
  text-align: right;
}

/* 合计行样式优化 */
.el-table__footer-wrapper .el-table__row {
  background-color: #f5f7fa;
  font-weight: 600;
}
</style>